package com.ctrip.ec.api.mobile.common;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by cannon on 2018/3/26.
 */
public class JsonBodyMethodProcessor implements HandlerMethodReturnValueHandler {
    public boolean supportsReturnType(MethodParameter methodParameter) {
        JsonBody jsonBody = methodParameter.getMethodAnnotation(JsonBody.class);
        if (jsonBody != null) {
            return jsonBody.value();
        } else {
            return true;
        }
//        boolean flag = methodParameter.getMethodAnnotation(JsonBody.class) != null;
//        return flag;
    }

    public void handleReturnValue(final Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        modelAndViewContainer.setRequestHandled(true);

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        String status = ResponseStatus.SUCCESS.getId() + "";
        String message = "success";
        long count = -1;

        if (RequestContext.getResponseHeaderStatus() != null) {
            status = RequestContext.getResponseHeaderStatus() + "";
        }

        if (RequestContext.getResponseHeaderMessage() != null) {
            message = RequestContext.getResponseHeaderMessage();
        }

        ResultBody value = new ResultBody(status, message, o, RequestContext.getResponseHeaderPager());

        //需要清理header
        RequestContext.clearResponseHeader();


        JsonSerializer.write(value, methodParameter.getMethod(), request, response);


    }
}
